// 账单管理组件

class BillsComponent {
    constructor() {
        this.accounts = []; // 存储账户信息
        this.init();
    }
    
    init() {
        // 绑定事件
        this.bindEvents();
        // 加载账户信息
        this.loadAccounts();
        // 设置默认值
        this.setDefaultValues();
    }
    
    // 设置默认值
    setDefaultValues() {
        // 设置默认日期为今天
        const today = new Date().toISOString().split('T')[0];
        const billDate = document.getElementById('billDate');
        if (billDate) {
            billDate.value = today;
        }
    }
    
    bindEvents() {
        // 绑定账单表单提交事件
        const billForm = document.getElementById('billForm');
        if (billForm) {
            billForm.addEventListener('submit', (e) => this.handleBillSubmit(e));
        }
        
        // 绑定账单类型切换事件
        const billType = document.getElementById('billType');
        if (billType) {
            billType.addEventListener('change', (e) => this.handleTypeChange(e));
        }
        
        // 绑定重置按钮事件
        const resetBillForm = document.getElementById('resetBillForm');
        if (resetBillForm) {
            resetBillForm.addEventListener('click', () => this.resetForm());
        }
        
        // 使用事件委托绑定编辑和删除按钮事件
        document.addEventListener('click', (e) => {
            // 编辑按钮事件
            if (e.target.classList.contains('edit-bill-btn')) {
                const billId = e.target.getAttribute('data-bill-id');
                this.editBill(billId);
            }
            
            // 删除按钮事件
            if (e.target.classList.contains('delete-bill-btn')) {
                const billId = e.target.getAttribute('data-bill-id');
                this.deleteBill(billId);
            }
        });
        
        // 页面加载完成后设置默认值
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setDefaultValues());
        } else {
            this.setDefaultValues();
        }
    }
    
    // 重置表单
    resetForm() {
        const billForm = document.getElementById('billForm');
        if (billForm) {
            billForm.reset();
            
            // 重新设置默认值
            document.getElementById('billType').value = 'expense';
            document.getElementById('billCategory').value = '2';
            this.setDefaultValues();
            
            // 隐藏转账账户选择
            const transferAccounts = document.getElementById('transferAccounts');
            if (transferAccounts) {
                transferAccounts.style.display = 'none';
            }
            
            // 显示分类选择
            const categoryGroup = document.getElementById('categoryGroup');
            if (categoryGroup) {
                categoryGroup.style.display = 'block';
            }
        }
    }
    
    // 处理账单类型切换
    handleTypeChange(e) {
        const type = e.target.value;
        const transferAccounts = document.getElementById('transferAccounts');
        const categoryGroup = document.getElementById('categoryGroup');
        
        if (type === 'transfer') {
            // 显示账户选择，隐藏分类选择
            transferAccounts.style.display = 'block';
            categoryGroup.style.display = 'none';
            // 填充账户选择列表
            this.populateAccountSelects();
        } else {
            // 隐藏账户选择，显示分类选择
            transferAccounts.style.display = 'none';
            categoryGroup.style.display = 'block';
        }
    }
    
    // 加载账户信息
    async loadAccounts() {
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                return;
            }
            
            const response = await fetch('http://localhost:3003/api/accounts', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            this.accounts = data.accounts || [];
        } catch (error) {
            console.error('加载账户信息失败:', error);
        }
    }
    
    // 填充账户选择列表
    populateAccountSelects() {
        const sourceAccountSelect = document.getElementById('sourceAccount');
        const targetAccountSelect = document.getElementById('targetAccount');
        
        if (!sourceAccountSelect || !targetAccountSelect) return;
        
        // 清空现有选项
        sourceAccountSelect.innerHTML = '<option value="">请选择源账户</option>';
        targetAccountSelect.innerHTML = '<option value="">请选择目标账户</option>';
        
        // 添加账户选项
        this.accounts.forEach(account => {
            if (account.is_active) {
                const option1 = document.createElement('option');
                option1.value = account.id;
                option1.textContent = account.name;
                sourceAccountSelect.appendChild(option1);
                
                const option2 = document.createElement('option');
                option2.value = account.id;
                option2.textContent = account.name;
                targetAccountSelect.appendChild(option2);
            }
        });
    }
    
    // 处理账单提交
    async handleBillSubmit(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const billType = formData.get('type');
        let billData;
        
        if (billType === 'transfer') {
            // 转账类型处理
            billData = {
                type: billType,
                amount: parseFloat(formData.get('amount')),
                title: formData.get('title') || '转账',
                bill_date: formData.get('date'),
                account_id: formData.get('sourceAccount'),
                transfer_to_account_id: formData.get('targetAccount')
            };
            
            // 验证转账必需字段
            if (!billData.account_id) {
                this.showMessage('请选择源账户', 'error');
                return;
            }
            
            if (!billData.transfer_to_account_id) {
                this.showMessage('请选择目标账户', 'error');
                return;
            }
            
            if (billData.account_id === billData.transfer_to_account_id) {
                this.showMessage('源账户和目标账户不能相同', 'error');
                return;
            }
        } else {
            // 收入/支出类型处理
            billData = {
                type: billType,
                amount: parseFloat(formData.get('amount')),
                category_id: formData.get('categoryId'),
                title: formData.get('title'),
                description: formData.get('description'),
                bill_date: formData.get('date')
            };
            
            // 验证必填字段
            if (!billData.title) {
                this.showMessage('请输入标题', 'error');
                return;
            }
            
            if (!billData.category_id) {
                this.showMessage('请选择分类', 'error');
                return;
            }
        }
        
        if (!billData.bill_date) {
            this.showMessage('请选择日期', 'error');
            return;
        }
        
        try {
            const result = await this.submitBill(billData);
            
            if (result.success) {
                this.showMessage('记账成功', 'success');
                // 重置表单
                e.target.reset();
                
                // 重新设置默认值
                document.getElementById('billType').value = 'expense';
                document.getElementById('billCategory').value = '2';
                this.setDefaultValues();
                
                // 隐藏转账账户选择
                const transferAccounts = document.getElementById('transferAccounts');
                if (transferAccounts) {
                    transferAccounts.style.display = 'none';
                }
                
                // 显示分类选择
                const categoryGroup = document.getElementById('categoryGroup');
                if (categoryGroup) {
                    categoryGroup.style.display = 'block';
                }
                
                // 重新加载账单列表
                this.loadBills();
            } else {
                this.showMessage(result.error, 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Bill submit error:', error);
        }
    }
    
    // 获取最近账单
    async getRecentBills(limit = 5) {
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                throw new Error('用户未登录');
            }
            
            const response = await fetch(`http://localhost:3003/api/bills?limit=${limit}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            return data.bills || [];
        } catch (error) {
            console.error('获取最近账单失败:', error);
            return [];
        }
    }
    
    // 获取所有账单
    async getAllBills() {
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                throw new Error('用户未登录');
            }
            
            const response = await fetch('http://localhost:3003/api/bills', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            return data.bills || [];
        } catch (error) {
            console.error('获取账单列表失败:', error);
            return [];
        }
    }
    
    // 渲染最近账单列表
    renderRecentBills(bills) {
        const recentBillsContainer = document.getElementById('recentBills');
        if (!recentBillsContainer) return;
        
        if (!bills || bills.length === 0) {
            recentBillsContainer.innerHTML = '<p>暂无账单记录</p>';
            return;
        }
        
        let billsHtml = '';
        bills.forEach(bill => {
            const date = new Date(bill.bill_date).toLocaleDateString('zh-CN');
            const amount = parseFloat(bill.amount).toFixed(2);
            let amountColor, amountSign, categoryName;
            
            if (bill.type === 'income') {
                amountColor = '#0f0';
                amountSign = '+';
                categoryName = bill.category_name || '收入';
            } else if (bill.type === 'expense') {
                amountColor = '#f00';
                amountSign = '-';
                categoryName = bill.category_name || '支出';
            } else if (bill.type === 'transfer') {
                amountColor = '#00f';
                amountSign = '';
                categoryName = `${bill.account_name || '账户'} → ${bill.transfer_to_account_name || '账户'}`;
            }
            
            billsHtml += `
                <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.1);">
                    <div>
                        <h4 style="margin: 0;">${bill.title}</h4>
                        <p style="margin: 5px 0 0 0; font-size: 0.9rem; color: #aaa;">${date}</p>
                    </div>
                    <div style="text-align: right;">
                        <p style="margin: 0; font-size: 1.1rem; color: ${amountColor};">${amountSign}${bill.type !== 'transfer' ? '¥' : ''}${amount}</p>
                        <p style="margin: 5px 0 0 0; font-size: 0.9rem; color: #aaa;">${categoryName}</p>
                    </div>
                </div>
            `;
        });
        
        recentBillsContainer.innerHTML = billsHtml;
    }
    
    // 渲染账单列表
    renderBills(bills) {
        const billListContainer = document.querySelector('#billsPage .bill-list');
        if (!billListContainer) return;
        
        if (!bills || bills.length === 0) {
            billListContainer.innerHTML = '<p class="no-data">暂无账单记录</p>';
            return;
        }
        
        let billsHtml = '';
        bills.forEach(bill => {
            const date = new Date(bill.bill_date).toLocaleDateString('zh-CN');
            const amount = parseFloat(bill.amount).toFixed(2);
            let amountColor, amountSign, categoryName;
            
            if (bill.type === 'income') {
                amountColor = '#0f0';
                amountSign = '+';
                categoryName = bill.category_name || '收入';
            } else if (bill.type === 'expense') {
                amountColor = '#f00';
                amountSign = '-';
                categoryName = bill.category_name || '支出';
            } else if (bill.type === 'transfer') {
                amountColor = '#00f';
                amountSign = '';
                categoryName = `${bill.account_name || '账户'} → ${bill.transfer_to_account_name || '账户'}`;
            }
            
            billsHtml += `
                <div class="card" data-bill-id="${bill.id}">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h3>${bill.title}</h3>
                            <p>${date}</p>
                        </div>
                        <div style="text-align: right;">
                            <p style="color: ${amountColor}; font-size: 1.2rem;">${amountSign}${bill.type !== 'transfer' ? '¥' : ''}${amount}</p>
                            <p>${categoryName}</p>
                        </div>
                        <div style="display: flex; gap: 5px;">
                            <button class="btn edit-bill-btn" data-bill-id="${bill.id}" style="padding: 5px 10px; font-size: 0.8rem;">编辑</button>
                            <button class="btn delete-bill-btn" data-bill-id="${bill.id}" style="padding: 5px 10px; font-size: 0.8rem; background-color: var(--accent-color);">删除</button>
                        </div>
                    </div>
                </div>
            `;
        });
        
        billListContainer.innerHTML = billsHtml;
    }
    
    // 加载并显示最近账单
    async loadRecentBills() {
        try {
            const bills = await this.getRecentBills(5);
            this.renderRecentBills(bills);
        } catch (error) {
            console.error('加载最近账单失败:', error);
            const recentBillsContainer = document.getElementById('recentBills');
            if (recentBillsContainer) {
                recentBillsContainer.innerHTML = '<p>加载账单失败</p>';
            }
        }
    }
    
    // 加载并显示所有账单
    async loadBills() {
        try {
            const bills = await this.getAllBills();
            this.renderBills(bills);
        } catch (error) {
            console.error('加载账单列表失败:', error);
            const billListContainer = document.querySelector('#billsPage .bill-list');
            if (billListContainer) {
                billListContainer.innerHTML = '<p class="no-data">加载账单失败</p>';
            }
        }
    }
    
    // 提交账单
    async submitBill(billData) {
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                throw new Error('用户未登录');
            }
            
            // 调用后端API
            const response = await fetch('http://localhost:3003/api/bills', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(billData)
            });
            
            const data = await response.json();
            
            if (response.ok) {
                // 重新加载最近账单
                this.loadRecentBills();
                
                // 重新加载仪表板数据
                if (window.dashboardComponent) {
                    window.dashboardComponent.loadDashboardData();
                }
                
                return { success: true, data };
            } else {
                return { success: false, error: data.error || '记账失败' };
            }
        } catch (error) {
            console.error('提交账单失败:', error);
            return { success: false, error: '网络错误，请稍后重试' };
        }
    }
    
    // 编辑账单
    async editBill(billId) {
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                this.showMessage('用户未登录', 'error');
                return;
            }
            
            // 获取账单详情
            const response = await fetch(`http://localhost:3003/api/bills/${billId}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            const bill = data.bill;
            
            // 填充表单数据
            document.getElementById('billType').value = bill.type;
            document.getElementById('billAmount').value = bill.amount;
            document.getElementById('billTitle').value = bill.title;
            document.getElementById('billDate').value = bill.bill_date.split('T')[0];
            
            if (bill.type === 'transfer') {
                // 处理转账类型
                const transferAccounts = document.getElementById('transferAccounts');
                const categoryGroup = document.getElementById('categoryGroup');
                
                if (transferAccounts) transferAccounts.style.display = 'block';
                if (categoryGroup) categoryGroup.style.display = 'none';
                
                // 填充账户选择
                this.populateAccountSelects();
                document.getElementById('sourceAccount').value = bill.account_id;
                document.getElementById('targetAccount').value = bill.transfer_to_account_id;
            } else {
                // 处理收入/支出类型
                document.getElementById('billCategory').value = bill.category_id;
                document.getElementById('billDescription').value = bill.description || '';
                
                const transferAccounts = document.getElementById('transferAccounts');
                const categoryGroup = document.getElementById('categoryGroup');
                
                if (transferAccounts) transferAccounts.style.display = 'none';
                if (categoryGroup) categoryGroup.style.display = 'block';
            }
            
            // 滚动到表单顶部
            document.getElementById('billForm').scrollIntoView({ behavior: 'smooth' });
            
            // 更改表单提交处理程序以更新账单
            const billForm = document.getElementById('billForm');
            if (billForm) {
                // 移除旧的事件监听器
                billForm.removeEventListener('submit', (e) => this.handleBillSubmit(e));
                // 添加新的事件监听器用于更新
                billForm.onsubmit = (e) => this.handleUpdateBill(e, billId);
            }
            
            this.showMessage('请修改账单信息后点击记账按钮保存', 'info');
        } catch (error) {
            console.error('获取账单详情失败:', error);
            this.showMessage('获取账单详情失败，请稍后重试', 'error');
        }
    }
    
    // 处理账单更新
    async handleUpdateBill(e, billId) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const billType = formData.get('type');
        let billData;
        
        if (billType === 'transfer') {
            // 转账类型处理
            billData = {
                type: billType,
                amount: parseFloat(formData.get('amount')),
                title: formData.get('title') || '转账',
                bill_date: formData.get('date'),
                account_id: formData.get('sourceAccount'),
                transfer_to_account_id: formData.get('targetAccount')
            };
            
            // 验证转账必需字段
            if (!billData.account_id) {
                this.showMessage('请选择源账户', 'error');
                return;
            }
            
            if (!billData.transfer_to_account_id) {
                this.showMessage('请选择目标账户', 'error');
                return;
            }
            
            if (billData.account_id === billData.transfer_to_account_id) {
                this.showMessage('源账户和目标账户不能相同', 'error');
                return;
            }
        } else {
            // 收入/支出类型处理
            billData = {
                type: billType,
                amount: parseFloat(formData.get('amount')),
                category_id: formData.get('categoryId'),
                title: formData.get('title'),
                description: formData.get('description'),
                bill_date: formData.get('date')
            };
            
            // 验证必填字段
            if (!billData.title) {
                this.showMessage('请输入标题', 'error');
                return;
            }
            
            if (!billData.category_id) {
                this.showMessage('请选择分类', 'error');
                return;
            }
        }
        
        if (!billData.bill_date) {
            this.showMessage('请选择日期', 'error');
            return;
        }
        
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                this.showMessage('用户未登录', 'error');
                return;
            }
            
            // 调用后端API更新账单
            const response = await fetch(`http://localhost:3003/api/bills/${billId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(billData)
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.showMessage('账单更新成功', 'success');
                // 重置表单
                e.target.reset();
                
                // 重新设置默认值
                document.getElementById('billType').value = 'expense';
                document.getElementById('billCategory').value = '2';
                this.setDefaultValues();
                
                // 隐藏转账账户选择
                const transferAccounts = document.getElementById('transferAccounts');
                if (transferAccounts) {
                    transferAccounts.style.display = 'none';
                }
                
                // 显示分类选择
                const categoryGroup = document.getElementById('categoryGroup');
                if (categoryGroup) {
                    categoryGroup.style.display = 'block';
                }
                
                // 恢复表单提交处理程序
                e.target.onsubmit = null;
                e.target.addEventListener('submit', (e) => this.handleBillSubmit(e));
                
                // 重新加载账单列表
                this.loadBills();
                
                // 重新加载最近账单
                this.loadRecentBills();
                
                // 重新加载仪表板数据
                if (window.dashboardComponent) {
                    window.dashboardComponent.loadDashboardData();
                }
            } else {
                this.showMessage(data.error || '账单更新失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Bill update error:', error);
        }
    }
    
    // 删除账单
    async deleteBill(billId) {
        try {
            const token = localStorage.getItem('authToken');
            if (!token) {
                this.showMessage('用户未登录', 'error');
                return;
            }
            
            // 确认删除
            if (!confirm('确定要删除这个账单吗？')) {
                return;
            }
            
            // 调用后端API删除账单
            const response = await fetch(`http://localhost:3003/api/bills/${billId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });
            
            const data = await response.json();
            
            if (response.ok) {
                this.showMessage('账单删除成功', 'success');
                // 重新加载账单列表
                this.loadBills();
                // 重新加载最近账单
                this.loadRecentBills();
                // 重新加载仪表板数据
                if (window.dashboardComponent) {
                    window.dashboardComponent.loadDashboardData();
                }
            } else {
                this.showMessage(data.error || '账单删除失败', 'error');
            }
        } catch (error) {
            this.showMessage('网络错误，请稍后重试', 'error');
            console.error('Bill delete error:', error);
        }
    }
    
    // 显示消息
    showMessage(message, type) {
        // 创建消息元素
        const messageEl = document.createElement('div');
        messageEl.className = `message message-${type}`;
        messageEl.textContent = message;
        
        // 添加样式
        Object.assign(messageEl.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '15px 20px',
            borderRadius: '5px',
            color: 'white',
            fontWeight: 'bold',
            zIndex: '1000',
            boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
            transition: 'opacity 0.3s'
        });
        
        if (type === 'success') {
            messageEl.style.backgroundColor = '#4CAF50';
        } else if (type === 'info') {
            messageEl.style.backgroundColor = '#2196F3';
        } else {
            messageEl.style.backgroundColor = '#F44336';
        }
        
        // 添加到页面
        document.body.appendChild(messageEl);
        
        // 3秒后淡出并移除
        setTimeout(() => {
            messageEl.style.opacity = '0';
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.parentNode.removeChild(messageEl);
                }
            }, 300);
        }, 3000);
    }
}

// 初始化账单组件
document.addEventListener('DOMContentLoaded', () => {
    window.billsComponent = new BillsComponent();
});